package com.zzyl.framework.interceptor;

import com.zzyl.common.nursing.service.impl.MemberThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: LiuLi
 * @Date: 2025/08/20 15:53
 * @Description:
 */
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    /**
     * 登录拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //1.获取请求的token
        String token = request.getHeader("authorization");
        //2.验证token
        if (token == null) {
            log.info("请求未携带token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("请求未携带token");
        }
        try {
            //3.验证token
            Claims claims = tokenService.parseToken(token);
            if (claims == null) {
                log.error("token验证失败");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                throw new RuntimeException("token验证失败");
            }
            //4.验证memberId
            Object memberId = claims.get("memberId");
            if (memberId == null) {
                log.error("token验证失败");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                throw new RuntimeException("token验证失败");
            }
            //5.验证成功,设置memberId
            MemberThreadLocal.setMemberId(Long.valueOf(memberId.toString()));
            log.info("token验证成功,登录的老人家属Id:{}", memberId);
        } catch (Exception e) {
            log.error("token验证失败,异常信息:{}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    /**
     * 释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MemberThreadLocal.remove();
    }
}
